package com.niu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.niu.constant.StatusConstant;
import com.niu.context.BaseContext;
import com.niu.dto.CategoryDTO;
import com.niu.dto.CategoryPageQueryDTO;
import com.niu.entity.Category;
import com.niu.mapper.CategoryMapper;
import com.niu.mapper.ProductMapper;
import com.niu.result.PageResult;
import com.niu.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    private static final Logger log = LoggerFactory.getLogger(CategoryServiceImpl.class);
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 修改分类
     * @param categoryDTO
     */
    @Override
    public void fix(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    /**
     * 分类分页查询
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO);
        long total = page.getTotal();
        List<Category> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 启用、禁用分类
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Category category = new Category();
        category.setId(id);
        category.setStatus(status);
        categoryMapper.update(category);
    }

    /**
     * 新增分类
     * @param categoryDTO
     */
    @Override
    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setUpdateTime(LocalDateTime.now());
        category.setStatus(StatusConstant.ENABLE);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());
        categoryMapper.insert(category);

    }

    /**
     * 根据id删除
     * @param id
     */
    @Override
    public void delete(Long id) {
        Integer count = productMapper.countByCategoryId(id);
        log.info("当前分类下关联了{}个商品", count);
        if (count > 0) {
            productMapper.deleteByCategoryId(id);
        }
        categoryMapper.delete(id);
    }


}
